﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ResourceOwnerPasswordCredentialGrantDemo
{

    class Program
    {
        static void Main(string[] args)
        {
            OauthTest oauthTest = new OauthTest();
            //oauthTest.Test();
            //oauthTest.Test1();
            oauthTest.GetAccessTokenByRefreshTokenTest().Wait();
            Console.ReadKey();
        }
    }

    public class OauthTest
    {
        private string clientId = "6677";
        private string clientSecret = "1";
        private HttpClient _httpClient;

        //private string AuthorizationServerBaseAddress= "http://localhost:44246/";
        //private string myPath = "api/Values";

        private string AuthorizationServerBaseAddress = "http://localhost:51073";
        private string myPath = "api/Hello/";
        private string myPath1 = "api/Hello/1";

        public OauthTest()
        {
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri(AuthorizationServerBaseAddress);
        }

        private async Task<string> GetAccessToken()
        {
        //    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
        //"Basic",
        //Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret)));

            var parameters = new Dictionary<string, string>();
            parameters.Add("client_id", clientId);
            parameters.Add("client_secret", clientSecret);
            parameters.Add("grant_type", "client_credentials");

            var data = new FormUrlEncodedContent(parameters);
            //Console.WriteLine(data);
            var response = await _httpClient.PostAsync("/token", data);
            var responseValue = await response.Content.ReadAsStringAsync();

            //Console.WriteLine(responseValue);

            return JObject.Parse(responseValue)["access_token"].Value<string>();
        }
        public async Task Test()
        {
            Console.WriteLine();

            var token = GetAccessToken().Result;
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);

            Console.WriteLine(await (await _httpClient.GetAsync(myPath)).Content.ReadAsStringAsync());
        }

        private async Task<string> GetAccessToken1()
        {
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
        "Basic",
        Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret)));

            var parameters = new Dictionary<string, string>();
            parameters.Add("grant_type", "password");
            parameters.Add("username", "账号");
            parameters.Add("password", "密码");

            //grant_type=password&username=candoo&password=candoo

            var response = await _httpClient.PostAsync("/token", new FormUrlEncodedContent(parameters));
            var responseValue = await response.Content.ReadAsStringAsync();

            //Console.WriteLine(JObject.Parse(responseValue)["access_token"].Value<string>());

            return JObject.Parse(responseValue)["access_token"].Value<string>();
        }
        public async Task Test1()
        {
            var token = GetAccessToken1().Result;
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);//bearer
            //Console.WriteLine(_httpClient.DefaultRequestHeaders);
            Console.WriteLine(await (await _httpClient.GetAsync(myPath1)).Content.ReadAsStringAsync());
        }

        public async Task GetAccessTokenByRefreshTokenTest()
        {
            //var clientId = "[clientId]";
            //var clientSecret = "[clientSecret]";

            var parameters = new Dictionary<string, string>();
            parameters.Add("grant_type", "refresh_token");
            parameters.Add("refresh_token", "cd89a9ad6d0344fdafd3f6dc5dc80e5a");

            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                "Basic",
                Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret)));

            var response = await _httpClient.PostAsync("/token", new FormUrlEncodedContent(parameters));
            var responseValue = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseValue);
        }
    }

}
